# -*- encoding: utf-8 -*-
import os
import requests


home      = "http://downloads.arduino.cc/"

winzip    = "arduino-%s-windows.zip"
winexe    = "arduino-%s-windows.exe"
mac_os    = "arduino-%s-macosx.zip"
linux_32  = "arduino-%s-linux32.tar.xz"
linux_64  = "arduino-%s-linux64.tar.xz"
linux_arm = "arduino-%s-linuxarm.tar.xz"

def getNotes():
    if not os.path.exists("log"): os.makedirs("log")

    url = "https://www.arduino.cc/en/Main/ReleaseNotes"
    r = requests.get(url)
    s = r.text

    f = open("log/notes.html", "w")
    f.write(s)
    f.close()

def getRelease(os_type):
    f = open("log/notes.html", "r")
    ls = f.readlines()
    f.close()
    os = os_type
    t = os.split("-")[2]
    t = t.replace(".", "-")
    s  = ""
    s2 = ""
    for l in ls:
        if "ARDUINO" in l[:7]:
            l   = l.strip()
            l   = l.replace(' - ', ' ')
            r   = l.split(" ")
            tit = r[0]
            if len(r) > 1:
                ver = r[1]
            else:
                ver = ""
            dat = "---"
            bate = ""
            if ver != "" and ver[:1] == "0":
                continue
            if len(r) > 3:
                #bate = r[2]
                dat  = r[3]
            elif len(r) > 2:
                dat = r[2]
            else:
                dat = ""
                #continue
            #print(l)
            u = home + os % ver
            s_t = "%s-%s %" + str(10-len(ver)) + "s %s%"+str(5-len(bate))+"s %s %"+str(10-len(dat))+"s %s"
            s_l = s_t % (tit, ver, " ", bate, " ", dat, " ", u)
            print(s_l)
            s += s_l + "\n"
            s2 += "<p><a href='%s%s' target='_blank'>%s</p>" % (home, os % ver, l)

    f = open("log/arduino_downlist_%s.txt" % t, "w")
    f.write(s)
    f.close()
    
    f = open("log/arduino_downlist_%s.html" % t, "w")
    f.write(s2)
    f.close()

if __name__ == "__main__":
    getNotes()

    getRelease(winzip)
    #getRelease(winexe)
    #getRelease(mac_os)
    #getRelease(linux_32)
    #getRelease(linux_64)
    #getRelease(linux_arm)

    print("finish!")
